package com.ruixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruixun.common.PageData;
import com.ruixun.entity.Role;
import com.ruixun.mapper.RoleMapper;
import com.ruixun.query.RolePageQuery;
import com.ruixun.rvo.RoleRvo;
import com.ruixun.service.RoleService;
import com.ruixun.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 * @author ruixun
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;

    @Override
    public PageData<RoleRvo> getRolePage(RolePageQuery query) {
        // 构建分页对象
        IPage<Role> page = new Page<>(query.getPageNum(), query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getDeleted, "0"); // 未删除的数据

        // 角色名称模糊查询
        if (StringUtils.hasText(query.getName())) {
            wrapper.like(Role::getName, query.getName());
        }

        // 角色类型等值查询
        if (StringUtils.hasText(query.getType())) {
            wrapper.eq(Role::getType, query.getType());
        }

        // 排序（按创建时间倒序）
        wrapper.orderByDesc(Role::getCreateTime);

        // 执行分页查询
        IPage<Role> rolePage = roleMapper.selectPage(page, wrapper);

        // 转换结果
        List<RoleRvo> rvoList = rolePage.getRecords().stream()
                .map(this::convertToRvo)
                .collect(Collectors.toList());
        return new PageUtils<RoleRvo>().convert(page.getCurrent(),page.getSize(),page.getTotal(),rvoList);
    }

    @Override
    public boolean addRole(Role role) {
        return save(role);
    }

    @Override
    public boolean updateRole(Role role) {
        return updateById(role);
    }

    @Override
    public boolean deleteRole(Long id) {
        Role role = getById(id);
        if (role != null) {
            role.setDeleted(1); // 逻辑删除
            return updateById(role);
        }
        return false;
    }

    @Override
    public RoleRvo getRoleById(Long id) {
        Role role = getById(id);
        return role != null ? convertToRvo(role) : null;
    }

    /**
     * 实体类转换为返回视图对象
     * @param role 角色实体
     * @return 返回视图对象
     */
    private RoleRvo convertToRvo(Role role) {
        RoleRvo rvo = new RoleRvo();
        BeanUtils.copyProperties(role, rvo);
        return rvo;
    }

}